'use strict';

    angular.module('app')
        .controller('accountUpdateController', ['$scope', '$rootScope', '$state', '$timeout','toaster',
                                             function($scope, $rootScope, $state, $timeout,toaster) {
        $scope.record = {};
        $scope.record.isShowSmsCode = false;//将验证码输入框设置为隐藏
        $scope.record.id = {};
        $scope.title = "账号设置";
        validate();
        activate();
        $scope.submit= function(){
            var m = $scope.record;
            var ps2 = $('#password1').val();
            if(m.password_==null){
            	toaster.clear('*');
            	toaster.pop('error', '', '新密码不能为空！');
            	return;
            }else if(ps2==null){
            	toaster.clear('*');
            	toaster.pop('error', '', '确认新密码不能为空！');
            	return;
            }else if(m.password_ !=ps2){
            	toaster.clear('*');
            	toaster.pop('error', '', '两次输入密码不一致！');
            	return;
            }else if($scope.phoneChange && m.smsCode==null){
            	toaster.clear('*');
            	toaster.pop('error', '', '验证码不能为空！');
            	return;
            }else{
            	if(m){

                    $scope.record.sign = base64Encode($scope.record.id+$scope.record.account_+$scope.record.password_);
            	    console.log($scope.record.sign);
            	    // return;

                    $scope.loading = true;
                    $scope.isDisabled = true;//提交disabled
                    $.ajax({
        				type: 'POST',
        	            dataType: 'json',
        				contentType:'application/json;charset=UTF-8',
        				url : '/user/update/account',
        				data: angular.toJson($scope.record)
        			}).then(function(result){
                         $scope.loading = false;
        				if(result.httpCode ==200){//成功
	                        alert("保存成功,请重新登录");
	                        $timeout(function(){
	                            $state.go('access.login');
	                        },1500);
	                    }else{
	                        toaster.clear('*');
	                        toaster.pop('error', '', result.msg);
	                        $scope.isDisabled = false;
	                    }
        			});
                }
            }
        }

        var originPNumber;//全局變量
        // 初始化页面
        function activate() {
	        $scope.loading = true;
        	$.ajax({
        		type: 'PUT',
	            dataType: 'json',
				contentType:'application/json;charset=UTF-8',
				url : '/user/read/accountDetail',
				data: angular.toJson($scope.record)
			}).then(function(result) {
		        $scope.loading = false;
				if (result.httpCode == 200) {
					$scope.record = result.data;
					$scope.record.id = result.data.id_;
                    //设置密码框默认提示值，供后台判断使用
                    $scope.record.password_ = 'v!l?%yM#';
                    $scope.record.password1 = 'v!l?%yM#';
                    //初始化完成時獲取初始手機號
                    originPNumber =$scope.record.phone_ ;
				} else {
					$scope.msg = result.msg;
				}
				$scope.$apply();
			});

        }

        //检测手机号码变化时做相应的交互
         var PhoneReg = /^[1][3,4,5,7,8][0-9]{9}$/;
        $scope.blur = function () {
            var nowPhone = $('#phone_').val();
            if(nowPhone==originPNumber){
                //console.log('號碼沒有變')
            }else if(nowPhone !== originPNumber&&(PhoneReg.test(nowPhone))) {
                //console.log('新號碼為：'+nowPhone)
                $scope.phoneChange = true;
                $('#phone_').parent().addClass('changeWidth');
            }
        }
        //手机获取验证码
    	$scope.getSmsCode = function (phone_) {
            if(phone_ == null || phone_ == undefined){
                toaster.clear('*');
                toaster.pop('error', '', '手机号码不能为空');
            }
    		if((phone_ !== null && PhoneReg.test(phone_))){
                $scope.isShowSmsCode = true;//将验证码输入框设置为显示
    			$.ajax({
        			type: 'POST',
                    dataType: 'json',
        			contentType:'application/json;charset=UTF-8',
        			url : '/user/account/getSmsCode',
        			data: angular.toJson($scope.record)
        		}).then(function (result) {
                    $scope.loading = false;
                    if (result.httpCode == 200) {
                    	toaster.clear('*');
                        toaster.pop('success', '', "验证码已发送，请注意接收！");
                        var obj = $('#getCode');
                        var countdown=60;
                        settime(obj,countdown);//调用倒计时
                    } else {
                    	toaster.clear('*');
                        toaster.pop('error', '', result.msg);
                    }
                    $scope.$apply();
                });
    		}

    	}
    	//验证码倒计时
        function settime(obj,countdown) {
            if (countdown == 0) {
                resetButton();
                obj.removeAttr("disabled");
                obj.html("获取验证码");
                countdown = 60;
                return;
            } else {
                obj.html("重新发送" + countdown);
                obj.attr("disabled", true);
                countdown--;
            }
            setTimeout(function() {
                settime(obj,countdown)
            },1000)
        }
    	function resetButton(){
            //倒計時完成重置變量隱藏按鈕機輸入框
            $scope.isShowSmsCode = $scope.phoneChange= false;
            $('#phone_').parent().removeClass('changeWidth');
            $scope.$apply();
        }
        //表单验证
        function validate(){
            jQuery('form').validate({
                rules: {
                	user_name: {
                        required: true
                    },
                    phone_: {
                        required: true,
                        digits: true
                    },
                    smsCode: {
                        required: true
                    },
                    password_: {
                        required: true
                    },
                    password1: {
                        required: true
                    }
                },
                messages: {
                	user_name: {
                    	required: '请输入姓名'
                    },
                    phone_: {
                        required: '请输入手机号码',
                        digits: '请输入正确的手机号码'
                    },
                    smsCode: {
                        required: '请输入验证码'
                    },
                    password_: {
                        required: '请设置新密码'
                    },
                    password1: {
                        required: '请确认密码'
                    }
                },
                submitHandler: function() {
                    $scope.submit();
                }
            });
        }

        function base64Encode(input) {
            var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            input = _utf8_encode(input);
            while (i < input.length) {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);
                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;
                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }
                output = output +
                    _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                    _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
            }
            return output;
        }

        function _utf8_encode(string){
            string = string.replace(/\r\n/g,"\n");
            var utftext = "";
            for (var n = 0; n < string.length; n++) {
                var c = string.charCodeAt(n);
                if (c < 128) {
                    utftext += String.fromCharCode(c);
                } else if((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                } else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }
            }
            return utftext;
        }

    }]);